/**
 * API模块 - 重构版本
 * 使用新的日志系统和网络管理器
 */

// 创建API模块的日志器
const apiLogger = window.logger ? window.logger.createContextLogger('API') : console;

/**
 * API客户端类
 */
class ApiClient {
    constructor() {
        this.baseUrl = window.envConfig ? window.envConfig.getApiBaseUrl() : 'http://localhost:3000';
        this.networkManager = window.networkManager;
        this.migrationManager = window.dataMigrationManager;
        
        apiLogger.info('API客户端已初始化', { baseUrl: this.baseUrl });
    }
    
    /**
     * 发送HTTP请求
     * @private
     * @param {string} endpoint - API端点
     * @param {Object} options - 请求选项
     * @returns {Promise<Object>} 响应数据
     */
    async _request(endpoint, options = {}) {
        const url = `${this.baseUrl}${endpoint}`;
        const requestOptions = {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        };
        
        apiLogger.debug(`发送请求: ${options.method || 'GET'} ${url}`);
        
        try {
            const response = await fetch(url, requestOptions);
            
            if (!response.ok) {
                throw new Error(`请求失败: ${response.status} ${response.statusText}`);
            }
            
            const data = await response.json();
            apiLogger.debug(`请求成功: ${options.method || 'GET'} ${endpoint}`);
            return data;
        } catch (error) {
            apiLogger.error(`请求失败: ${options.method || 'GET'} ${endpoint}`, error);
            
            // 如果网络不可用，添加到同步队列
            if (this.networkManager && !this.networkManager.getStatus().isOnline) {
                apiLogger.info('网络不可用，添加到同步队列');
                this.networkManager.addSyncTask({
                    type: options.method || 'GET',
                    endpoint,
                    data: options.body ? JSON.parse(options.body) : null
                });
            }
            
            throw error;
        }
    }
    
    /**
     * 获取任务列表
     * @returns {Promise<Array>} 任务列表
     */
    async getTasks() {
        return this._request('/api/tasks');
    }
    
    /**
     * 添加任务
     * @param {Object} task - 任务对象
     * @returns {Promise<Object>} 添加的任务
     */
    async addTask(task) {
        const logger = apiLogger.createContextLogger ? apiLogger.createContextLogger('AddTask') : apiLogger;
        
        try {
            // 检查网络状态
            if (this.networkManager && !this.networkManager.getStatus().isOnline) {
                logger.info('网络不可用，将任务添加到离线队列');
                
                // 生成本地ID
                const localTask = {
                    ...task,
                    id: 'local_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
                    createdAt: new Date().toISOString(),
                    updatedAt: new Date().toISOString(),
                    needsSync: true
                };
                
                // 添加到离线操作队列
                await this.networkManager.addOfflineOperation('create', 'tasks', null, localTask);
                
                // 保存到本地存储
                this._saveTaskToLocalStorage(localTask);
                
                return localTask;
            }
            
            // 网络可用，直接发送请求
            const response = await this._request('/api/tasks', {
                method: 'POST',
                body: JSON.stringify(task)
            });
            
            logger.info('任务添加成功', response);
            
            // 更新本地存储
            this._saveTaskToLocalStorage(response);
            
            return response;
        } catch (error) {
            logger.error('添加任务失败:', error);
            
            // 如果是网络错误，尝试添加到离线队列
            if (this._isNetworkError(error) && this.networkManager) {
                logger.info('检测到网络错误，将任务添加到离线队列');
                
                const localTask = {
                    ...task,
                    id: 'local_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
                    createdAt: new Date().toISOString(),
                    updatedAt: new Date().toISOString(),
                    needsSync: true
                };
                
                await this.networkManager.addOfflineOperation('create', 'tasks', null, localTask);
                this._saveTaskToLocalStorage(localTask);
                
                return localTask;
            }
            
            throw error;
        }
    }
    
    /**
     * 更新任务
     * @param {string} id - 任务ID
     * @param {Object} updates - 更新数据
     * @returns {Promise<Object>} 更新后的任务
     */
    async updateTask(id, updates) {
        const logger = apiLogger.createContextLogger ? apiLogger.createContextLogger('UpdateTask') : apiLogger;
        
        try {
            // 获取当前任务数据
            const currentTask = this._getTaskFromLocalStorage(id) || await this.getTasks().then(tasks => tasks.find(t => t.id === id));
            if (!currentTask) {
                throw new Error('任务不存在');
            }
            
            // 合并更新数据
            const updatedTask = {
                ...currentTask,
                ...updates,
                updatedAt: new Date().toISOString()
            };
            
            // 检查网络状态
            if (this.networkManager && !this.networkManager.getStatus().isOnline) {
                logger.info('网络不可用，将任务更新添加到离线队列');
                
                // 更新本地存储
                this._saveTaskToLocalStorage(updatedTask);
                
                // 添加到离线操作队列
                await this.networkManager.addOfflineOperation('update', 'tasks', id, updatedTask);
                
                return updatedTask;
            }
            
            // 网络可用，直接发送请求
            const response = await this._request(`/api/tasks/${id}`, {
                method: 'PUT',
                body: JSON.stringify(updatedTask)
            });
            
            logger.info('任务更新成功', response);
            
            // 更新本地存储
            this._saveTaskToLocalStorage(response);
            
            return response;
        } catch (error) {
            logger.error('更新任务失败:', error);
            
            // 如果是网络错误，尝试添加到离线队列
            if (this._isNetworkError(error) && this.networkManager) {
                logger.info('检测到网络错误，将任务更新添加到离线队列');
                
                // 获取本地任务数据
                const localTask = this._getTaskFromLocalStorage(id);
                if (localTask) {
                    const updatedTask = {
                        ...localTask,
                        ...updates,
                        updatedAt: new Date().toISOString(),
                        needsSync: true
                    };
                    
                    this._saveTaskToLocalStorage(updatedTask);
                    await this.networkManager.addOfflineOperation('update', 'tasks', id, updatedTask);
                    
                    return updatedTask;
                }
            }
            
            throw error;
        }
    }
    
    /**
     * 删除任务
     * @param {string} id - 任务ID
     * @returns {Promise<Object>} 删除结果
     */
    async deleteTask(id) {
        const logger = apiLogger.createContextLogger ? apiLogger.createContextLogger('DeleteTask') : apiLogger;
        
        try {
            // 检查网络状态
            if (this.networkManager && !this.networkManager.getStatus().isOnline) {
                logger.info('网络不可用，将任务删除添加到离线队列');
                
                // 从本地存储删除
                this._removeTaskFromLocalStorage(id);
                
                // 添加到离线操作队列
                await this.networkManager.addOfflineOperation('delete', 'tasks', id, null);
                
                return { success: true };
            }
            
            // 网络可用，直接发送请求
            const response = await this._request(`/api/tasks/${id}`, {
                method: 'DELETE'
            });
            
            logger.info('任务删除成功');
            
            // 从本地存储删除
            this._removeTaskFromLocalStorage(id);
            
            return response;
        } catch (error) {
            logger.error('删除任务失败:', error);
            
            // 如果是网络错误，尝试添加到离线队列
            if (this._isNetworkError(error) && this.networkManager) {
                logger.info('检测到网络错误，将任务删除添加到离线队列');
                
                this._removeTaskFromLocalStorage(id);
                await this.networkManager.addOfflineOperation('delete', 'tasks', id, null);
                
                return { success: true };
            }
            
            throw error;
        }
    }
    
    /**
     * 获取笔记列表
     * @returns {Promise<Array>} 笔记列表
     */
    async getNotes() {
        return this._request('/api/notes');
    }
    
    /**
     * 添加笔记
     * @param {Object} note - 笔记对象
     * @returns {Promise<Object>} 添加的笔记
     */
    async addNote(note) {
        const logger = apiLogger.createContextLogger ? apiLogger.createContextLogger('AddNote') : apiLogger;
        
        try {
            // 检查网络状态
            if (this.networkManager && !this.networkManager.getStatus().isOnline) {
                logger.info('网络不可用，将笔记添加到离线队列');
                
                // 生成本地ID
                const localNote = {
                    ...note,
                    id: 'local_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
                    createdAt: new Date().toISOString(),
                    updatedAt: new Date().toISOString(),
                    needsSync: true
                };
                
                // 添加到离线操作队列
                await this.networkManager.addOfflineOperation('create', 'notes', null, localNote);
                
                // 保存到本地存储
                this._saveNoteToLocalStorage(localNote);
                
                return localNote;
            }
            
            // 网络可用，直接发送请求
            const response = await this._request('/api/notes', {
                method: 'POST',
                body: JSON.stringify(note)
            });
            
            logger.info('笔记添加成功', response);
            
            // 更新本地存储
            this._saveNoteToLocalStorage(response);
            
            return response;
        } catch (error) {
            logger.error('添加笔记失败:', error);
            
            // 如果是网络错误，尝试添加到离线队列
            if (this._isNetworkError(error) && this.networkManager) {
                logger.info('检测到网络错误，将笔记添加到离线队列');
                
                const localNote = {
                    ...note,
                    id: 'local_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
                    createdAt: new Date().toISOString(),
                    updatedAt: new Date().toISOString(),
                    needsSync: true
                };
                
                await this.networkManager.addOfflineOperation('create', 'notes', null, localNote);
                this._saveNoteToLocalStorage(localNote);
                
                return localNote;
            }
            
            throw error;
        }
    }
    
    /**
     * 更新笔记
     * @param {string} id - 笔记ID
     * @param {Object} updates - 更新数据
     * @returns {Promise<Object>} 更新后的笔记
     */
    async updateNote(id, updates) {
        const logger = apiLogger.createContextLogger ? apiLogger.createContextLogger('UpdateNote') : apiLogger;
        
        try {
            // 获取当前笔记数据
            const currentNote = this._getNoteFromLocalStorage(id) || await this.getNotes().then(notes => notes.find(n => n.id === id));
            if (!currentNote) {
                throw new Error('笔记不存在');
            }
            
            // 合并更新数据
            const updatedNote = {
                ...currentNote,
                ...updates,
                updatedAt: new Date().toISOString()
            };
            
            // 检查网络状态
            if (this.networkManager && !this.networkManager.getStatus().isOnline) {
                logger.info('网络不可用，将笔记更新添加到离线队列');
                
                // 更新本地存储
                this._saveNoteToLocalStorage(updatedNote);
                
                // 添加到离线操作队列
                await this.networkManager.addOfflineOperation('update', 'notes', id, updatedNote);
                
                return updatedNote;
            }
            
            // 网络可用，直接发送请求
            const response = await this._request(`/api/notes/${id}`, {
                method: 'PUT',
                body: JSON.stringify(updatedNote)
            });
            
            logger.info('笔记更新成功', response);
            
            // 更新本地存储
            this._saveNoteToLocalStorage(response);
            
            return response;
        } catch (error) {
            logger.error('更新笔记失败:', error);
            
            // 如果是网络错误，尝试添加到离线队列
            if (this._isNetworkError(error) && this.networkManager) {
                logger.info('检测到网络错误，将笔记更新添加到离线队列');
                
                // 获取本地笔记数据
                const localNote = this._getNoteFromLocalStorage(id);
                if (localNote) {
                    const updatedNote = {
                        ...localNote,
                        ...updates,
                        updatedAt: new Date().toISOString(),
                        needsSync: true
                    };
                    
                    this._saveNoteToLocalStorage(updatedNote);
                    await this.networkManager.addOfflineOperation('update', 'notes', id, updatedNote);
                    
                    return updatedNote;
                }
            }
            
            throw error;
        }
    }
    
    /**
     * 删除笔记
     * @param {string} id - 笔记ID
     * @returns {Promise<Object>} 删除结果
     */
    async deleteNote(id) {
        const logger = apiLogger.createContextLogger ? apiLogger.createContextLogger('DeleteNote') : apiLogger;
        
        try {
            // 检查网络状态
            if (this.networkManager && !this.networkManager.getStatus().isOnline) {
                logger.info('网络不可用，将笔记删除添加到离线队列');
                
                // 从本地存储删除
                this._removeNoteFromLocalStorage(id);
                
                // 添加到离线操作队列
                await this.networkManager.addOfflineOperation('delete', 'notes', id, null);
                
                return { success: true };
            }
            
            // 网络可用，直接发送请求
            const response = await this._request(`/api/notes/${id}`, {
                method: 'DELETE'
            });
            
            logger.info('笔记删除成功');
            
            // 从本地存储删除
            this._removeNoteFromLocalStorage(id);
            
            return response;
        } catch (error) {
            logger.error('删除笔记失败:', error);
            
            // 如果是网络错误，尝试添加到离线队列
            if (this._isNetworkError(error) && this.networkManager) {
                logger.info('检测到网络错误，将笔记删除添加到离线队列');
                
                this._removeNoteFromLocalStorage(id);
                await this.networkManager.addOfflineOperation('delete', 'notes', id, null);
                
                return { success: true };
            }
            
            throw error;
        }
    }
    
    /**
     * 获取设置
     * @returns {Promise<Object>} 设置对象
     */
    async getSettings() {
        return this._request('/api/settings');
    }
    
    /**
     * 更新设置
     * @param {Object} settings - 设置对象
     * @returns {Promise<Object>} 更新后的设置
     */
    async updateSettings(settings) {
        const logger = apiLogger.createContextLogger ? apiLogger.createContextLogger('UpdateSettings') : apiLogger;
        
        try {
            // 检查网络状态
            if (this.networkManager && !this.networkManager.getStatus().isOnline) {
                logger.info('网络不可用，将设置更新添加到离线队列');
                
                // 保存到本地存储
                this._saveSettingsToLocalStorage(settings);
                
                // 添加到离线操作队列
                await this.networkManager.addOfflineOperation('update', 'settings', 'user', settings);
                
                return settings;
            }
            
            // 网络可用，直接发送请求
            const response = await this._request('/api/settings', {
                method: 'PUT',
                body: JSON.stringify(settings)
            });
            
            logger.info('设置更新成功', response);
            
            // 更新本地存储
            this._saveSettingsToLocalStorage(response);
            
            return response;
        } catch (error) {
            logger.error('更新设置失败:', error);
            
            // 如果是网络错误，尝试添加到离线队列
            if (this._isNetworkError(error) && this.networkManager) {
                logger.info('检测到网络错误，将设置更新添加到离线队列');
                
                this._saveSettingsToLocalStorage(settings);
                await this.networkManager.addOfflineOperation('update', 'settings', 'user', settings);
                
                return settings;
            }
            
            throw error;
        }
    }
    
    /**
     * 判断是否为网络错误
     * @private
     * @param {Error} error - 错误对象
     * @returns {boolean} 是否为网络错误
     */
    _isNetworkError(error) {
        // 检查常见的网络错误特征
        return (
            error.message.includes('Network Error') ||
            error.message.includes('fetch') ||
            error.message.includes('Failed to fetch') ||
            error.message.includes('ERR_NETWORK') ||
            error.message.includes('ERR_INTERNET_DISCONNECTED') ||
            error.name === 'NetworkError' ||
            (error.name === 'TypeError' && error.message.includes('Failed to fetch'))
        );
    }
    
    /**
     * 保存任务到本地存储
     * @private
     * @param {Object} task - 任务对象
     */
    _saveTaskToLocalStorage(task) {
        try {
            const tasks = JSON.parse(localStorage.getItem('tasks') || '[]');
            const existingIndex = tasks.findIndex(t => t.id === task.id);
            
            if (existingIndex >= 0) {
                tasks[existingIndex] = task;
            } else {
                tasks.push(task);
            }
            
            localStorage.setItem('tasks', JSON.stringify(tasks));
        } catch (error) {
            apiLogger.error('保存任务到本地存储失败:', error);
        }
    }
    
    /**
     * 从本地存储获取任务
     * @private
     * @param {string} id - 任务ID
     * @returns {Object|null} 任务对象
     */
    _getTaskFromLocalStorage(id) {
        try {
            const tasks = JSON.parse(localStorage.getItem('tasks') || '[]');
            return tasks.find(t => t.id === id) || null;
        } catch (error) {
            apiLogger.error('从本地存储获取任务失败:', error);
            return null;
        }
    }
    
    /**
     * 从本地存储删除任务
     * @private
     * @param {string} id - 任务ID
     */
    _removeTaskFromLocalStorage(id) {
        try {
            const tasks = JSON.parse(localStorage.getItem('tasks') || '[]');
            const filteredTasks = tasks.filter(t => t.id !== id);
            localStorage.setItem('tasks', JSON.stringify(filteredTasks));
        } catch (error) {
            apiLogger.error('从本地存储删除任务失败:', error);
        }
    }
    
    /**
     * 保存笔记到本地存储
     * @private
     * @param {Object} note - 笔记对象
     */
    _saveNoteToLocalStorage(note) {
        try {
            const notes = JSON.parse(localStorage.getItem('notes') || '[]');
            const existingIndex = notes.findIndex(n => n.id === note.id);
            
            if (existingIndex >= 0) {
                notes[existingIndex] = note;
            } else {
                notes.push(note);
            }
            
            localStorage.setItem('notes', JSON.stringify(notes));
        } catch (error) {
            apiLogger.error('保存笔记到本地存储失败:', error);
        }
    }
    
    /**
     * 从本地存储获取笔记
     * @private
     * @param {string} id - 笔记ID
     * @returns {Object|null} 笔记对象
     */
    _getNoteFromLocalStorage(id) {
        try {
            const notes = JSON.parse(localStorage.getItem('notes') || '[]');
            return notes.find(n => n.id === id) || null;
        } catch (error) {
            apiLogger.error('从本地存储获取笔记失败:', error);
            return null;
        }
    }
    
    /**
     * 从本地存储删除笔记
     * @private
     * @param {string} id - 笔记ID
     */
    _removeNoteFromLocalStorage(id) {
        try {
            const notes = JSON.parse(localStorage.getItem('notes') || '[]');
            const filteredNotes = notes.filter(n => n.id !== id);
            localStorage.setItem('notes', JSON.stringify(filteredNotes));
        } catch (error) {
            apiLogger.error('从本地存储删除笔记失败:', error);
        }
    }
    
    /**
     * 保存设置到本地存储
     * @private
     * @param {Object} settings - 设置对象
     */
    _saveSettingsToLocalStorage(settings) {
        try {
            const currentSettings = JSON.parse(localStorage.getItem('settings') || '{}');
            const updatedSettings = { ...currentSettings, ...settings };
            localStorage.setItem('settings', JSON.stringify(updatedSettings));
        } catch (error) {
            apiLogger.error('保存设置到本地存储失败:', error);
        }
    }
    
    /**
     * 检查API健康状态
     * @returns {Promise<boolean>} API是否健康
     */
    async checkHealth() {
        try {
            await this._request('/health');
            return true;
        } catch (error) {
            apiLogger.error('API健康检查失败:', error);
            return false;
        }
    }
}

/**
 * 数据迁移功能
 */
class DataMigration {
    constructor() {
        this.apiClient = new ApiClient();
        this.logger = window.logger ? window.logger.createContextLogger('DataMigration') : console;
        this.lastMigrationTime = localStorage.getItem('lastMigrationTime') || null;
        this.isMigrating = false;
    }
    
    /**
     * 执行数据迁移
     * @returns {Promise<Object>} 迁移结果
     */
    async migrate() {
        if (this.isMigrating) {
            this.logger.info('数据迁移正在进行中，跳过本次迁移');
            return { status: 'skipped', reason: 'already_migrating' };
        }
        
        try {
            this.isMigrating = true;
            this.logger.info('开始数据迁移');
            
            // 检查API健康状态
            const isApiHealthy = await this.apiClient.checkHealth();
            if (!isApiHealthy) {
                this.logger.warn('API不可用，跳过数据迁移');
                return { status: 'skipped', reason: 'api_unhealthy' };
            }
            
            // 执行迁移
            const result = await this._performMigration();
            
            // 更新迁移时间
            if (result.hasChanges) {
                this.lastMigrationTime = new Date().toISOString();
                localStorage.setItem('lastMigrationTime', this.lastMigrationTime);
                this.logger.info('数据迁移完成，更新迁移时间', { lastMigrationTime: this.lastMigrationTime });
            }
            
            return result;
        } catch (error) {
            this.logger.error('数据迁移失败:', error);
            return { status: 'error', error: error.message };
        } finally {
            this.isMigrating = false;
        }
    }
    
    /**
     * 执行实际的数据迁移
     * @private
     * @returns {Promise<Object>} 迁移结果
     */
    async _performMigration() {
        const result = {
            hasChanges: false,
            tasksMigrated: 0,
            notesMigrated: 0,
            settingsMigrated: 0
        };
        
        // 获取本地数据
        const localData = this._getLocalData();
        
        // 获取服务器数据
        const serverData = await this._getServerData();
        
        // 迁移任务
        const taskResult = await this._migrateTasks(localData.tasks, serverData.tasks);
        result.tasksMigrated = taskResult.count;
        result.hasChanges = result.hasChanges || taskResult.hasChanges;
        
        // 迁移笔记
        const noteResult = await this._migrateNotes(localData.notes, serverData.notes);
        result.notesMigrated = noteResult.count;
        result.hasChanges = result.hasChanges || noteResult.hasChanges;
        
        // 迁移设置
        const settingsResult = await this._migrateSettings(localData.settings, serverData.settings);
        result.settingsMigrated = settingsResult.count;
        result.hasChanges = result.hasChanges || settingsResult.hasChanges;
        
        this.logger.info('数据迁移完成', result);
        
        return result;
    }
    
    /**
     * 获取本地数据
     * @private
     * @returns {Object} 本地数据
     */
    _getLocalData() {
        try {
            return {
                tasks: JSON.parse(localStorage.getItem('tasks') || '[]'),
                notes: JSON.parse(localStorage.getItem('notes') || '[]'),
                settings: JSON.parse(localStorage.getItem('settings') || '{}')
            };
        } catch (error) {
            this.logger.error('获取本地数据失败:', error);
            return {
                tasks: [],
                notes: [],
                settings: {}
            };
        }
    }
    
    /**
     * 获取服务器数据
     * @private
     * @returns {Promise<Object>} 服务器数据
     */
    async _getServerData() {
        try {
            const [tasks, notes, settings] = await Promise.all([
                this.apiClient.getTasks(),
                this.apiClient.getNotes(),
                this.apiClient.getSettings()
            ]);
            
            return { tasks, notes, settings };
        } catch (error) {
            this.logger.error('获取服务器数据失败:', error);
            return {
                tasks: [],
                notes: [],
                settings: {}
            };
        }
    }
    
    /**
     * 迁移任务数据
     * @private
     * @param {Array} localTasks - 本地任务
     * @param {Array} serverTasks - 服务器任务
     * @returns {Promise<Object>} 迁移结果
     */
    async _migrateTasks(localTasks, serverTasks) {
        let count = 0;
        let hasChanges = false;
        
        // 创建服务器任务ID映射
        const serverTaskIds = new Set(serverTasks.map(task => task.id));
        
        // 筛选出需要迁移的任务
        const tasksToMigrate = localTasks.filter(task => {
            // 如果任务不在服务器上，需要迁移
            if (!serverTaskIds.has(task.id)) {
                return true;
            }
            
            // 如果任务更新时间晚于上次迁移时间，需要迁移
            if (this.lastMigrationTime && task.updatedAt) {
                const taskUpdatedAt = new Date(task.updatedAt);
                const lastMigration = new Date(this.lastMigrationTime);
                if (taskUpdatedAt > lastMigration) {
                    return true;
                }
            }
            
            return false;
        });
        
        // 迁移任务
        for (const task of tasksToMigrate) {
            try {
                await this.apiClient.addTask(task);
                count++;
                hasChanges = true;
                this.logger.debug('任务迁移成功:', task.id);
            } catch (error) {
                this.logger.error('任务迁移失败:', task.id, error);
            }
        }
        
        return { count, hasChanges };
    }
    
    /**
     * 迁移笔记数据
     * @private
     * @param {Array} localNotes - 本地笔记
     * @param {Array} serverNotes - 服务器笔记
     * @returns {Promise<Object>} 迁移结果
     */
    async _migrateNotes(localNotes, serverNotes) {
        let count = 0;
        let hasChanges = false;
        
        // 创建服务器笔记ID映射
        const serverNoteIds = new Set(serverNotes.map(note => note.id));
        
        // 筛选出需要迁移的笔记
        const notesToMigrate = localNotes.filter(note => {
            // 如果笔记不在服务器上，需要迁移
            if (!serverNoteIds.has(note.id)) {
                return true;
            }
            
            // 如果笔记更新时间晚于上次迁移时间，需要迁移
            if (this.lastMigrationTime && note.updatedAt) {
                const noteUpdatedAt = new Date(note.updatedAt);
                const lastMigration = new Date(this.lastMigrationTime);
                if (noteUpdatedAt > lastMigration) {
                    return true;
                }
            }
            
            return false;
        });
        
        // 迁移笔记
        for (const note of notesToMigrate) {
            try {
                await this.apiClient.addNote(note);
                count++;
                hasChanges = true;
                this.logger.debug('笔记迁移成功:', note.id);
            } catch (error) {
                this.logger.error('笔记迁移失败:', note.id, error);
            }
        }
        
        return { count, hasChanges };
    }
    
    /**
     * 迁移设置数据
     * @private
     * @param {Object} localSettings - 本地设置
     * @param {Object} serverSettings - 服务器设置
     * @returns {Promise<Object>} 迁移结果
     */
    async _migrateSettings(localSettings, serverSettings) {
        let count = 0;
        let hasChanges = false;
        
        // 比较设置差异
        const settingsToMigrate = {};
        
        for (const [key, value] of Object.entries(localSettings)) {
            if (serverSettings[key] !== value) {
                settingsToMigrate[key] = value;
            }
        }
        
        // 如果有设置需要迁移
        if (Object.keys(settingsToMigrate).length > 0) {
            try {
                await this.apiClient.updateSettings(settingsToMigrate);
                count = Object.keys(settingsToMigrate).length;
                hasChanges = true;
                this.logger.debug('设置迁移成功:', settingsToMigrate);
            } catch (error) {
                this.logger.error('设置迁移失败:', error);
            }
        }
        
        return { count, hasChanges };
    }
}

// 创建API实例
const api = {
    client: new ApiClient(),
    migration: new DataMigration(),
    
    // 向后兼容的方法
    checkAPIHealth: () => api.client.checkHealth(),
    getTasks: () => api.client.getTasks(),
    addTask: (task) => api.client.addTask(task),
    updateTask: (id, updates) => api.client.updateTask(id, updates),
    deleteTask: (id) => api.client.deleteTask(id),
    getNotes: () => api.client.getNotes(),
    addNote: (note) => api.client.addNote(note),
    updateNote: (id, updates) => api.client.updateNote(id, updates),
    deleteNote: (id) => api.client.deleteNote(id),
    getSettings: () => api.client.getSettings(),
    updateSettings: (settings) => api.client.updateSettings(settings),
    migrateLocalStorageData: () => api.migration.migrate()
};

// 导出API模块
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { api, ApiClient, DataMigration };
} else {
    window.api = api;
    window.ApiClient = ApiClient;
    window.DataMigration = DataMigration;
}